home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: How do I write gets() function that checks for boundaries?
- Date: 8 Mar 1996 15:40:28 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4hqghcINNeh7@keats.ugrad.cs.ubc.ca>
- References: <313FDB9F.7455@cyberus.ca>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <313FDB9F.7455@cyberus.ca>, MC <mcardinal@cyberus.ca> wrote:
- >I want to write my own gets() function that will check string size so that it doesn't accept more
- >characters than my declared string variable. Any ideas?
-
- This feature is already implemented in fgets(). However, you want to know how
- it is done.
-
- Well, you simply read characters into the given buffer and keep advancing the
- pointer. If you have done this n-1 times, where n is the input parameter
- specifying the buffer size, or you have run out of input (EOF condition, or
- newline character encountered), you bail out of the loop. You affix a null
- character and you are done! Whether or not you choose to make the newline a
- part of the string is up to you, of course.
-
- A more interesting question might be, "how do I write a gets() function (call
- it vgets() for ``variable'') that accepts _aribitrary_ input without
- overflowing?"
-
- This you could do by using malloc() to allocate a buffer internal to vgets().
- You read into that buffer. When you have filled it up, you use realloc() to
- increase the size of the buffer as many times as you need to to read the whole
- line of text.
-
- When you are done, you can use realloc() one more time to trim down the space
- to what is actually consumed by the line. With this technique, you can handle
- files that have lines of arbitrary length.
-
- One of my pet peeves is text editor programs that limit the line length. The
- one I'm using right now, Vim, will let you load just about _anything_. I can
- pop a UNIX kernel into it, edit some strings, write it back and reboot.
- --
-
-